package org.springframework.beans.factory.annotation;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.util.BeanUtil;
import org.springframework.beans.util.ClassUtil;
import org.springframework.test.domain.TestProcessor;

import java.lang.reflect.Field;

/**
 * 自动注入bean处理器
 *
 * @author xiaohei
 */
public class AutowiredAnnotationBeanPostProcessor implements InstantiationAwareBeanPostProcessor, BeanFactoryAware {

    private ConfigurableListableBeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        Class clazz = bean.getClass();
        clazz = ClassUtil.isCglibProxyClass(clazz) ? clazz.getSuperclass() : clazz;

        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            Value valueAnno = field.getAnnotation(Value.class);
            if (valueAnno != null) {
                String value = valueAnno.value();
                // todo 暂时直接注入
                BeanUtil.setFieldValue(bean, field.getName(), value);
            }

            Autowired autowired = field.getAnnotation(Autowired.class);
            if (autowired != null) {
                Class<?> type = field.getType();
                Qualifier qualifier = field.getAnnotation(Qualifier.class);
                Object dependentBean;
                if (qualifier != null) {
                    String dependentBeanName = qualifier.value();
                    dependentBean = beanFactory.getBean(dependentBeanName, type);
                } else {
                    dependentBean = beanFactory.getBean(type);
                }
                BeanUtil.setFieldValue(bean, field.getName(), dependentBean);
            }
        }

        return pvs;
    }
}
